import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import type { ComputedRef } from 'vue'

/**
 *
 * 传入响应式参数
 * 动态创建流程需要的带参函数
 *
 */
export function useExecuteFlowService(
  props: ComputedRef<ExecuteFlowProcesParams>
) {
  const userStore = useUserStore()

  const { userInfo } = storeToRefs(userStore)
  /**
   * 执行审批
   * 1.第一次发起
   * 2.退回并提起审批
   */
  function processStartOrApproveRequest() {
    if (props.value.flowId) {
      return processApproveRequest()
    }

    return startProcessRequest()
  }

  function processApproveRequest(params: Recordable = {}) {
    return props.value.processApproveRequest({
      id: props.value.id,
      processDefinitionId: props.value.flowId,
      assignee: userInfo.value?.userId,
      ...params
    })
  }

  // 获取流程信息
  function getCurrentFlowEchoRequest() {
    return props.value.getFlowEchoRequest({
      id: props.value.id,
      prId: props.value.flowId
    })
  }

  // 拒绝
  function processRefuseRequest(params: Recordable = {}) {
    return props.value.processRefuseRequest({
      id: props.value.id,
      prId: props.value.flowId,
      assignee: userInfo.value?.userId,
      ...params
    })
  }

  // 开启流程
  function startProcessRequest(params: Recordable = {}) {
    return props.value.startProcessRequest({
      id: props.value.id,
      flowData: props.value.json,
      ...params
    })
  }

  return {
    processStartOrApproveRequest,
    processApproveRequest,
    getCurrentFlowEchoRequest,
    processRefuseRequest,
    startProcessRequest
  }
}

export type ExecuteFlowProcesParams = {
  id?: number | string

  json?: string
  // 当期启动流程的id
  flowId?: number | string
  // 开始流程请求
  startProcessRequest: (...args: any[]) => Promise<void>
  // 审批流程请求
  processApproveRequest: (...args: any[]) => Promise<void>
  // 退回流程请求
  processRefuseRequest: (...args: any[]) => Promise<void>
  // 获取当前流程信息
  getFlowEchoRequest: (...args: any[]) => Promise<void>
}
